package titt.io.writer;

import titt.head.Content;
import titt.head.response.ResponseHead;
import titt.io.encoding.Encoder;
import titt.io.socket.TITTSocket;
import titt.io.socket.out.LengthBufferedOutputStream;
import titt.type.TypedObject;

public class ResponseWriter implements Writer<TypedObject> {

	private final Encoder enc;
	private final TITTSocket ts;
	private final ResponseHead resp;
	
	public ResponseWriter(TITTSocket ts, Encoder enc, ResponseHead resp) {
		this.ts = ts;
		this.enc = enc;
		this.resp = resp;
	}
	
	@Override
	public void writeValues(TypedObject... values) throws Exception {
		LengthBufferedOutputStream buf = new LengthBufferedOutputStream();

		buf.write(enc.encode(values[0].getType(), values[0].getObject()));
		buf.flush();
		
		ts.getHeadWriter().writeHead(new Content(buf.getLength(), values[0].getType().asString(), resp));
		
		buf.writeTo(ts.getOutputStream());
		
		ts.getOutputStream().flush();
	}

}
